package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.service.MarketAdminService;
import com.cskaoyan.market.service.MarketAdminServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.JsonNode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin/admin/*")
public class AdminAdminController extends HttpServlet {
    private MarketAdminService marketAdminService = new MarketAdminServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/admin/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //接收用户提交过来的请求参数信息
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String username = req.getParameter("username");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        Integer page = null;
        Integer limit = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (NumberFormatException e) {
            Object object = ResponseUtil.badArgument();
            String s = JacksonUtil.getObjectMapper().writeValueAsString(object);
            resp.getWriter().println(s);
            return;
        }
        List<MarketAdmin> marketAdminList = marketAdminService.list(limit, page, username, sort, order);
        Object o = ResponseUtil.okList(marketAdminList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/admin/", "");
        if ("update".equals(op)) {
            update(req, resp);
        } else if ("create".equals(op)) {
            create(req,resp);
        } else if ("delete".equals(op)) {
            delete(req,resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        MarketAdmin marketAdmin = new MarketAdmin();
        String id = JacksonUtil.parseString(requestBody, "id");
        assert id != null;
        marketAdmin.setId(Integer.parseInt(id));
        marketAdminService.delete(marketAdmin);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketAdmin)));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        MarketAdmin marketAdmin = new MarketAdmin();
        String username = JacksonUtil.parseString(requestBody, "username");
        String password = JacksonUtil.parseString(requestBody, "password");
        String avatar = JacksonUtil.parseString(requestBody, "avatar");
        JsonNode jsonNode = JacksonUtil.getObjectMapper().readTree(requestBody);
        JsonNode roleIdsParm = jsonNode.get("roleIds");
        ArrayList<Integer> roleIdsList = new ArrayList<>();
        for (JsonNode roleId : roleIdsParm) {
            roleIdsList.add(roleId.asInt());
        }
        Integer[] roleIds = roleIdsList.toArray(new Integer[0]);
        marketAdmin.setUsername(username);
        marketAdmin.setPassword(password);
        marketAdmin.setAvatar(avatar);
        marketAdmin.setRoleIds(roleIds);
        marketAdmin.setAddTime(LocalDateTime.now());
        marketAdmin.setUpdateTime(LocalDateTime.now());
        marketAdminService.create(marketAdmin);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketAdmin)));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        MarketAdmin marketAdmin = new MarketAdmin();
        String id = JacksonUtil.parseString(requestBody, "id");
        String username = JacksonUtil.parseString(requestBody, "username");
        String password = JacksonUtil.parseString(requestBody, "password");
        String avatar = JacksonUtil.parseString(requestBody, "avatar");
        JsonNode jsonNode = JacksonUtil.getObjectMapper().readTree(requestBody);
        JsonNode roleIdsParm = jsonNode.get("roleIds");
        ArrayList<Integer> roleIdsList = new ArrayList<>();
        for (JsonNode roleId : roleIdsParm) {
            roleIdsList.add(roleId.asInt());
        }
        Integer[] roleIds = roleIdsList.toArray(new Integer[0]);
        marketAdmin.setId(Integer.parseInt(id));
        marketAdmin.setUsername(username);
        marketAdmin.setPassword(password);
        marketAdmin.setAvatar(avatar);
        marketAdmin.setRoleIds(roleIds);
        marketAdmin.setUpdateTime(LocalDateTime.now());
        marketAdminService.update(marketAdmin);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(marketAdmin)));
    }
}
